/*
 * $Id: DatabaseTreeModel.java 24 2009-03-31 23:40:10Z aaron.day $
 */
package org.crazydays.gameplan.data.swing.tree;


import java.io.File;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.crazydays.gameplan.data.Database;
import org.crazydays.gameplan.map.IGameMap;

/**
 * DatabaseTreeModel
 */
public class DatabaseTreeModel
        extends DefaultTreeModel
{
	/** serial version uid */
	public final static long serialVersionUID =
	        "$Id: DatabaseTreeModel.java 24 2009-03-31 23:40:10Z aaron.day $"
	                .hashCode();

	/** log */
	protected static Log LOG = LogFactory.getLog(DatabaseTreeModel.class);

	/**
	 * Build the database tree.
	 * 
	 * @param database Database
	 * @return Tree
	 */
	protected static MutableTreeNode build(Database database)
	{
		if (database == null) {
			throw new IllegalArgumentException("database == null");
		}

		MutableTreeNode root = root(database);

		// TODO: when additional types are added, add "maps" hierarchy

		// add maps
		for (IGameMap gameMap : database.getGameMaps()) {
			MutableTreeNode mapNode =
			        new DefaultMutableTreeNode(gameMap.getName());
			root.insert(mapNode, root.getChildCount());
		}

		return root;
	}

	/**
	 * Get database root node.
	 * 
	 * @param database Database
	 * @return Root
	 */
	protected static MutableTreeNode root(Database database)
	{
		if (database == null) {
			throw new IllegalArgumentException("database == null");
		}

		File file = database.getFile();
		if (file == null) {
			return new DefaultMutableTreeNode("Unsaved", true);
		} else {
			return new DefaultMutableTreeNode(file.getName()
			        .replaceAll("\\..*?$", ""), true);
		}
	}

	/** database */
	protected Database database;

	/**
	 * DatabaseTree constructor.
	 * 
	 * @param database Database
	 */
	public DatabaseTreeModel(Database database)
	{
		super(build(database), true);
		setDatabase(database);
	}

	/**
	 * Set database.
	 * 
	 * @param database Database
	 */
	public void setDatabase(Database database)
	{
		this.database = database;
	}

	/**
	 * Get database.
	 * 
	 * @return Database
	 */
	public Database getDatabase()
	{
		return database;
	}
}
